//
//  AccountVC.swift
//  mmda
//
//  Created by 李陆涛 on 2018/4/25.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class AccountVC: BaseTabVC {

    
    @IBOutlet weak var userLogo: UIImageView!
    
    @IBOutlet weak var userNameLabel: UILabel!
    
    var viewModel:AccountViewModel!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupData()
    }
    
    func setupUI() {
        
        self.view.backgroundColor = kContentColor
    }
    
    func setupData() {
        
        self.viewModel = AccountViewModel()
        
        self.viewModel.message.asObservable().bind(to: self.view.rx.showToast).disposed(by: disposeBag)
        
        self.viewModel.loadSuccess = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.reloadUI()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(loadUser), name: kLoginSuccessNotifationName, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(loadUser), name: kReloadUserNotifationName, object: nil)
        
        self.loadUser()
    }
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    
    
    func reloadUI() {
        
        self.userLogo.setImage(string: self.viewModel.user?.logo_new?.getQiniuThumb(thumbImageWidth), placeholder: #imageLiteral(resourceName: "default"))
        self.userNameLabel.text = self.viewModel.user?.nickname ?? self.viewModel.user?.username
    }
    
    @objc private func loadUser() {
        
        if hasLogin() {
            
            self.viewModel.start()
        }
    }
}

extension AccountVC {
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.row == 1 {
            
            let myBlogVC = BlogOrUserListVC(pageType: .mine, userid: AppManager.share.user?._id)
            
            self.show(myBlogVC, sender: nil)
        }
    }
    
    
}
